package com.gis.halodepok;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.gis.halodepok.R;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
public class AtmBca extends ListActivity {

	

	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		Item[] list=new Item[7];
//		list[0]= new Item ("KC Margonda","Jln. Margonda Raya No. 182","0217772930",null, -6.38657,106.828501);
//		list[1]= new Item ("KCP Bukit Cinere Indah ","Jln. Cinere Raya No. 20 C-1 & C-2 Cinere","0217532240",null, -6.337926,106.780822);
//		list[2]= new Item ("KCP Depok Asri","Ruko Depok No. 4 & 5, Jln. Tole Iskandar No. 40","02177833344",null, -6.406066,106.84438);
//		list[3]= new Item ("KCP Kelapa Dua","Ruko Golden Stik, Jln. Akses UI No. 26 Kelapa Dua","02187716201",null, -6.355158,106.84055);	
//		list[4]= new Item ("KCP Nusantara","Jln. Nusantara Raya No. 15","021-7750438",null, -6.390446,106.8142);
//		list[5]= new Item ("KCP Proklamasi Depok","Jln. Proklamasi Blok D No.15","0217702519",null, -6.390678,106.851389);
//		list[6]= new Item ("KCP Margo City","Margo City Unit GF 11, Jln. Margonda Raya No. 358","0217870342",null,-6.373125,106.833254);
		
		
		ArrayList<Item> items = readfilexml();
		Item[] list=new Item[items.size()];
		for (int i = 0; i < items.size(); i++) {
			list[i] = items.get(i);
		}
		
		LocationManager manager= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location networklocation= manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		Location gpslocation= manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		Location  mylocation=null;
		if (networklocation!=null)
		{ 
			mylocation=networklocation;
		    if (gpslocation!=null && gpslocation.getTime()> networklocation.getTime())
		    { 
		    	mylocation=gpslocation;
		    }
		}
		else if (gpslocation !=null)
		{
			mylocation=gpslocation;
		}
		setContentView(R.layout.listmenu);
		AdapterItem adapter=new AdapterItem (this,R.layout.list,list,mylocation);
		setListAdapter(adapter);
		registerForContextMenu(getListView());
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		super.onListItemClick(l, v, position, id);
		Item item=((AdapterItem)getListView().getAdapter()).getList()[position];	
		Intent intent=new Intent (Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/?f=d&saddr=&daddr="+item.getLat()+","+item.getLon()+" ("+item.getNama()+")"));
		startActivity(intent);
	}
	
	
	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_NAMA = "nama";
	static final String KEY_ALAMAT = "alamat";
	static final String KEY_BUKA = "buka";
	static final String KEY_TELP = "telp";
	static final String KEY_LAT = "lat";
	static final String KEY_LONG = "long";

	public Document getDomElement(String xml) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is);

		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}
		// return DOM
		return doc;
	}
	
	public String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return this.getElementValue(n.item(0));
	}

	public final String getElementValue(Node elem) {
		Node child;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (child = elem.getFirstChild(); child != null; child = child
						.getNextSibling()) {
					if (child.getNodeType() == Node.TEXT_NODE) {
						return child.getNodeValue();
					}
				}
			}
		}
		return "";
	}
	
	
	public ArrayList<Item> readfilexml(){
		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
		ArrayList<Item> items = new ArrayList<Item>();
        Document doc = getDomElement(readFromFile());
 
        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
           
            Item item = new Item(getValue(e, KEY_NAMA), getValue(e, KEY_ALAMAT), "","", Double.parseDouble(getValue(e, KEY_LAT)), Double.parseDouble(getValue(e, KEY_LONG)));
            items.add(item);
            
           
            
            map.put(KEY_NAMA, getValue(e, KEY_NAMA));
            map.put(KEY_ALAMAT, getValue(e, KEY_ALAMAT));
            map.put(KEY_LAT, getValue(e, KEY_LAT));
            map.put(KEY_LONG, getValue(e, KEY_LONG));
            
            // adding HashList to ArrayList
            System.err.println(map.get(KEY_NAMA)+"|"+map.get(KEY_ALAMAT));
            menuItems.add(map);
        }
        return items;
	}
	private String readFromFile() {

		String ret = "";

		try {
			File root =AtmBca.this.getDir("haha", Context.MODE_PRIVATE);

			File dir = new File(root.getAbsolutePath() + "/xmls/19.xml");
			FileInputStream inputStream = new FileInputStream(dir);
			if (inputStream != null) {
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream);
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);
				String receiveString = "";
				StringBuilder stringBuilder = new StringBuilder();

				while ((receiveString = bufferedReader.readLine()) != null) {
					stringBuilder.append(receiveString);
				}

				inputStream.close();
				ret = stringBuilder.toString();
				
			}
		} catch (FileNotFoundException e) {
			Log.e("login activity", "File not found: " + e.toString());
		} catch (IOException e) {
			Log.e("login activity", "Can not read file: " + e.toString());
		}

		return ret;
	}



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}